package com.example.demo.common;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Admin
 * Date: 2023-03-19
 * Time: 16:47
 */

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.apache.logging.log4j.message.ObjectArrayMessage;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

/**
 *统一数据返回封装
*/

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
       //如果截取过来的数据是HashMap的数据,说明已经被封装好了就不需要再次封装了
        if(body instanceof HashMap) {
            return body;
        }


        //单独处理String类型的数据,但是这种方式太绝对了,有些情况下返回的状态码或状态信息需要自定义,这种情况也需要考虑
        if(body instanceof String) {
            ObjectMapper objectMapper = new ObjectMapper();
            //通过ObjectMapper类的writeValueAsString方法把String类型的数据进行转换.
            return objectMapper.writeValueAsString(AjaxResult.success(body));
        }

        return AjaxResult.success(body);
    }
}
